package com.igeek.ch02.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/*
 *@author wangpeng
 *2023/7/20 11:42
 *@description TODO
 */
public class BaseDao<T> {
    private QueryRunner queryRunner = new QueryRunner();

    //增、删、改
    public int update(Connection conn,String sql, Object... params) throws SQLException {
        int i = queryRunner.update(conn,sql, params);
        return i;
    }

    //查询  查询单个值ScalarHandler
    public Object selectSingleValue(Connection conn,String sql,Object... params) throws SQLException {
        Object query = queryRunner.query(conn,sql,new ScalarHandler(),params);
        return query;
    }

    //查询  查询单个对象BeanHandler
    public T selectOne(Connection conn,String sql,Class<T> clazz,Object... params) throws SQLException {
        T t = queryRunner.query(conn,sql,new BeanHandler<>(clazz),params);
        return t;
    }

    //查询  查询多个对象BeanListHandler
    public List<T> selectAll(Connection conn,String sql,Class<T> clazz,Object... params) throws SQLException {
        List<T> list = queryRunner.query(conn,sql,new BeanListHandler<>(clazz),params);
        return list;
    }


    //查询  将多条记录封装到一个Map集合中，以List<Map<String, Object>>返回
    public List<Map<String,Object>> selectMap(Connection conn , String sql , Object... params) throws SQLException {
        //Map<String, Object> key字段名,value值
        List<Map<String, Object>> mapList = queryRunner.query(conn, sql, new MapListHandler(), params);
        return mapList;
    }
}
